package com.lmh.gpt.demo.service.impl;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.lmh.gpt.demo.model.ChatGptRequest;
import com.lmh.gpt.demo.model.ChatGptResponse;
import com.lmh.gpt.demo.model.Message;
import com.lmh.gpt.demo.service.ContextService;
import com.lmh.gpt.demo.util.Contant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.http.*;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.net.InetSocketAddress;
import java.net.Proxy;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;


@Service
public class ContextServiceImpl implements ContextService {
    @Autowired
    private Environment environment;
    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public String sendRequestWithContext(String question, ArrayList<String> context) {
        RestTemplate restTemplate = new RestTemplate();
        SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();

        // 设置代理主机和端口
        String proxyHost = environment.getProperty("http.proxy.host");
        int proxyPort = environment.getProperty("http.proxy.port", Integer.class);
        Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyHost, proxyPort));
        requestFactory.setProxy(proxy);

        restTemplate.setRequestFactory(requestFactory);


// 设置请求头
        // 设置请求头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.set("Authorization", "Bearer " + Contant.TOKEN);

        // 构建请求体对象
        ChatGptRequest requestBody = new ChatGptRequest();
        // 构建上下文消息
        List<String> messages = new ArrayList<>(context);
        List<Message> messageList = new ArrayList<>();
        // 添加上下文消息
        // 添加上下文消息
        for (int i = 0; i < context.size(); i++) {
            String messageContent = context.get(i);
            Message message = new Message();
            if (i % 2 == 0) {
                message.setRole("user");
            } else {
                message.setRole("assistant");
            }
            message.setContent(messageContent);
            messageList.add(message);
        }

        // 添加当前问题消息
        Message questionMessage = new Message();
        questionMessage.setRole("user");
        questionMessage.setContent(question);
        messageList.add(questionMessage);

        requestBody.setMessages(messageList);
        requestBody.setModel("gpt-3.5-turbo");


        // 创建 ObjectMapper 对象
        ObjectMapper objectMapper = new ObjectMapper();

        // 将请求体对象序列化为 JSON 字符串
        try {
            String requestBodyString = objectMapper.writeValueAsString(requestBody);
            HttpEntity<String> entity = new HttpEntity<>(requestBodyString, headers);

            ResponseEntity<String> response = restTemplate.exchange(Contant.GPTENDPOINT, HttpMethod.POST, entity, String.class);
            String body = response.getBody();
            System.out.println(body);

            // 创建ObjectMapper对象
            ObjectMapper objectMapper1 = new ObjectMapper();

            // 将JSON字符串转换为Java对象
            ChatGptResponse responseGPT = objectMapper1.readValue(body, ChatGptResponse.class);

            // 从Java对象中获取content值
            String content = responseGPT.getChoices().get(0).getMessage().getContent();
            // 在控制台输出content值
            System.out.println("Content: " + content);

            // 将问题和响应添加到上下文中
            String contextEntry = question + ";" + content;
            context.add(contextEntry);

            // 将更新后的上下文保存到Redis中
            saveContextToRedis(context);

            return content;
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public String sendRequestWithContext(String question) {
        RestTemplate restTemplate = new RestTemplate();
        SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();

        // 设置代理主机和端口
        String proxyHost = environment.getProperty("http.proxy.host");
        int proxyPort = environment.getProperty("http.proxy.port", Integer.class);
        Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyHost, proxyPort));
        requestFactory.setProxy(proxy);

        restTemplate.setRequestFactory(requestFactory);


// 设置请求头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.set("Authorization", "Bearer " + Contant.TOKEN);


        // 构建请求体对象
        ChatGptRequest requestBody = new ChatGptRequest();
        Message message1 = new Message();
        message1.setRole("user");
        message1.setContent(question);

        List<Message> messages = Collections.singletonList(message1);
        requestBody.setMessages(messages);
        requestBody.setModel("gpt-3.5-turbo");

        // 创建 ObjectMapper 对象
        ObjectMapper objectMapper = new ObjectMapper();

        // 将请求体对象序列化为 JSON 字符串
        try {
            String requestBodyString = objectMapper.writeValueAsString(requestBody);
            HttpEntity<String> entity = new HttpEntity<>(requestBodyString, headers);

            ResponseEntity<String> response = restTemplate.exchange(Contant.GPTENDPOINT, HttpMethod.POST, entity, String.class);
            String body = response.getBody();
            System.out.println(body);

            // 创建ObjectMapper对象
            ObjectMapper objectMapper1 = new ObjectMapper();

            // 将JSON字符串转换为Java对象
            ChatGptResponse responseGPT = objectMapper1.readValue(body, ChatGptResponse.class);

            // 从Java对象中获取content值
            String content = responseGPT.getChoices().get(0).getMessage().getContent();

            // 在控制台输出content值
            System.out.println("Content: " + content);


            return content;
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
    }


    private void saveContextToRedis(List<String> context) {
        String contextJson = String.join(";", context);
        ValueOperations<String, String> valueOps = redisTemplate.opsForValue();
        valueOps.set("chat_context", contextJson);
    }

}
